package com.hyfd.service.mp;

import java.io.File;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.util.DateUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.hyfd.common.BaseJson;
import com.hyfd.common.Echarts;
import com.hyfd.common.ExportExcelUtil;
import com.hyfd.common.FileDownload;
import com.hyfd.common.Page;
import com.hyfd.common.utils.DateTimeUtils;
import com.hyfd.common.utils.MapUtils;
import com.hyfd.common.utils.StringUtil;
import com.hyfd.dao.mp.AgentDao;
import com.hyfd.dao.mp.DataPkgDao;
import com.hyfd.dao.mp.ExceptionOrderDao;
import com.hyfd.dao.mp.OrderDao;
import com.hyfd.dao.mp.ProviderDao;
import com.hyfd.dao.mp.ProviderDataDispatcherDao;
import com.hyfd.dao.mp.ProviderPhysicalChannelDao;
import com.hyfd.dao.sys.SysUserRoleDao;
import com.hyfd.rabbitMq.RabbitMqProducer;
import com.hyfd.rabbitMq.SerializeUtil;
import com.hyfd.service.BaseService;

@Service
public class OrderSer extends BaseService
{
    
    public Logger log = Logger.getLogger(this.getClass());
    
    @Autowired
    OrderDao orderDao;
    
    @Autowired
    AgentDao agentDao;
    
    @Autowired
    ProviderPhysicalChannelDao providerPhysicalChannelDao;
    
    @Autowired
    ProviderDao providerDao;
    
    @Autowired
    chargeOrderSer chargeOrderSer;
    
    @Autowired
    RabbitMqProducer mqProducer;
    
    @Autowired
    ProviderAccountSer providerAccountSer;
    
    @Autowired
    ExceptionOrderDao exceptionOrderDao;
    
    @Autowired
    DataPkgDao dataPkgDao;
    
    @Autowired
    ProviderDataDispatcherDao providerDataDispatcherDao;
    
    @Autowired
    SysUserRoleDao sysUserRoleDao;
    
    public int getOrderCount(Map<String, Object> m)
    {
        int orderCount = 0;
        try
        {
            orderCount = orderDao.getOrderCount(m);
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return orderCount;
    }
    
    public String orderList(HttpServletRequest req)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            Map<String, Object> m = getMaps(req); // 封装前台参数为map
            Page p = getPage(m);// 提取分页参数
            int total = getOrderCount(m);
            p.setCount(total);
            int pageNum = p.getCurrentPage();
            int pageSize = p.getPageSize();
            
            sb.append("{");
            sb.append("" + getKey("page") + ":" + p.getCurrentPage() + ",");
            sb.append("" + getKey("total") + ":" + p.getNumCount() + ",");
            sb.append("" + getKey("records") + ":" + p.getCount() + ",");
            sb.append("" + getKey("rows") + ":" + "");
            
            PageHelper.startPage(pageNum, pageSize);// mybatis分页插件
            List<Map<String, Object>> dataList = orderDao.OrderList(m);
            String dataListJson = BaseJson.listToJson(dataList);
            sb.append(dataListJson);
            sb.append("}");
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return sb.toString();
    }
    
    public String orderListPage()
    {
        Map<String, Object> userInfoMap = getUser();
        String userid = userInfoMap.get("suId") + "";
        List<Map<String, Object>> dataList = sysUserRoleDao.getHasSysRoleList(userid);
        String agentRole = null;
        for (Map<String, Object> map : dataList)
        {
            String srName = map.get("srName") + "";
            if ("代理商".equals(srName))
            {
                agentRole = srName;
            }
        }
        Session session = getSession();
        session.setAttribute("agentRole", agentRole);
        return "mp/orderList";
    }
    
    /**
     * @功能描述： 根据条件获取订单列表数据并生成json
     *
     * @作者：HYJ @创建时间：2016年1月12日
     * @param req
     * @return
     */
    public String orderAllList(HttpServletRequest req)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            Map<String, Object> m = getMaps(req); // 封装前台参数为map
            Map<String, Object> userInfoMap = getUser();
            String userid = userInfoMap.get("suId") + "";
            // 根据用户Id查询agent表，若不为null则代表用户为代理商登陆
            Map<String, Object> agentMap = agentDao.selectByUserId(userid);
            if (agentMap != null)
            {
                // 得到代理商Id，查询其自身订单和其子集订单
                String agentParentId = agentMap.get("id") + "";
                m.put("agentParentId", agentParentId);
            }
            
            String agentName = (String)m.get("agentName");
            String dispatcherProviderName = (String)m.get("dispatcherProviderName");
            String providerName = (String)m.get("providerName");
            if (agentName != null && agentName != "")
            {
                Map<String, Object> agent = agentDao.selectByAgentNameForOrder(agentName);
                if (agent != null)
                {
                    String agentId = (String)agent.get("id");
                    m.put("agentId", agentId);
                }
                else
                {
                    m.put("agentId", agentName);
                }
            }
            if (dispatcherProviderName != null && dispatcherProviderName != "")
            {
                String dispatcherProviderId = providerPhysicalChannelDao.getProviderIdByName(dispatcherProviderName);
                if (dispatcherProviderId != null && dispatcherProviderId != "")
                {
                    m.put("dispatcherProviderId", dispatcherProviderId);
                }
                else
                {
                    m.put("dispatcherProviderId", dispatcherProviderName);
                }
            }
            if (providerName != null && providerName != "")
            {
                String providerId = providerDao.getIdByName(providerName);
                if (providerId != null && providerId != "")
                {
                    m.put("providerId", providerId);
                }
                else
                {
                    m.put("providerId", providerName);
                }
            }
            
            Page p = getPage(m);// 提取分页参数
            int total = getOrderCount(m);
            p.setCount(total);
            int pageNum = p.getCurrentPage();
            int pageSize = p.getPageSize();
            sb.append("{");
            sb.append("" + getKey("page") + ":" + p.getCurrentPage() + ",");
            sb.append("" + getKey("total") + ":" + p.getNumCount() + ",");
            sb.append("" + getKey("records") + ":" + p.getCount() + ",");
            sb.append("" + getKey("rows") + ":" + "");
            
            PageHelper.startPage(pageNum, pageSize);// mybatis分页插件
            List<Map<String, Object>> dataList = orderDao.selectAll(m);
            String dataListJson = BaseJson.listToJson(dataList);
            sb.append(dataListJson);
            sb.append("}");
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return sb.toString();
    }
    
    /**
     * 批量复充
     * */
    public String batchReCharge(HttpServletRequest request)
    {
        String id = request.getParameter("id");
        String suId = request.getParameter("suId");
        JSONObject json = new JSONObject();
        
        String[] ids = id.split(",");
        int succnum = 0, failnum = 0;
        int tianmaoNum = 0;
        // 判断是否天猫角色复充是否存在不是天猫的账单
        tianmaoNum = judgeTianmaoRole(suId, ids);
        // 大于0则返回
        if (tianmaoNum > 0)
        {
            json.put("succnum", succnum);
            json.put("failnum", failnum);
            json.put("tianmaoNum", tianmaoNum);
            return json.toJSONString();
        }
        for (int i = 0; i < ids.length; i++)
        {
            if (reCharge(ids[i]))
            {
                succnum++;
            }
            else
            {
                failnum++;
            }
        }
        json.put("succnum", succnum);
        json.put("failnum", failnum);
        return json.toJSONString();
    }
    
    /**
     * 批量退款
     * */
    public String batchReFund(HttpServletRequest request)
    {
        String id = request.getParameter("id");
        String suId = request.getParameter("suId");
        JSONObject json = new JSONObject();
        
        String[] ids = id.split(",");
        int succnum = 0, failnum = 0;
        int tianmaoNum = 0;
        // 判断是否天猫角色复充是否存在不是天猫的账单
        tianmaoNum = judgeTianmaoRole(suId, ids);
        // 大于0则返回
        if (tianmaoNum > 0)
        {
            json.put("succnum", succnum);
            json.put("failnum", failnum);
            json.put("tianmaoNum", tianmaoNum);
            return json.toJSONString();
        }
        for (int i = 0; i < ids.length; i++)
        {
            if (refund(ids[i]))
            {
                succnum++;
            }
            else
            {
                failnum++;
            }
        }
        
        json.put("succnum", succnum);
        json.put("failnum", failnum);
        json.put("tianmaoNum", tianmaoNum);
        return json.toJSONString();
    }
    
    /**
     * 复充方法
     * 
     * @author lks 2017年3月8日下午3:18:35
     * @param request
     * @return
     */
    public boolean reCharge(String id)
    {
        boolean flag = false;
        try
        {
            Map<String, Object> order = orderDao.selectById(id);// 获取异常订单
            if (order != null)
            {
                String orderStatus = order.get("status") + "";
                if (!orderStatus.equals("2") && !orderStatus.equals("3") && !orderStatus.equals("4"))
                {
                    chargeOrderSer.ReCharge(order);
                    flag = true;
                }
            }
        }
        catch (Exception e)
        {
            log.error("复充方法出错" + e);
        }
        return flag;
    }
    
    /**
     * 退款方法
     * 
     * @author lks 2017年3月8日下午3:18:51
     * @param request
     * @return
     */
    public boolean refund(String id)
    {
        boolean flag = false;
        Map<String, Object> order = orderDao.selectById(id);
        if (order != null)
        {
            String orderStatus = order.get("status") + "";
            if (!orderStatus.equals("2") && !orderStatus.equals("3") && !orderStatus.equals("4"))
            {
                flag = chargeOrderSer.dealOrderFail(order, "4", "人工退款处理");
                if (flag)
                {
                    Map<String, Object> callbackMap = new HashMap<String, Object>();
                    callbackMap.put("status", AgentCallbackSer.CallbackStatus_Fail);
                    callbackMap.put("order", order);
                    mqProducer.sendDataToQueue(RabbitMqProducer.Callback_QueueKey,
                        SerializeUtil.getStrFromObj(callbackMap));
                }
            }
        }
        return flag;
    }
    
    /**
     * 修改状态
     * 
     * @author lks 2017年4月22日下午1:47:14
     * @param request
     * @return
     */
    public String updateStatus(HttpServletRequest request)
    {
        String id = request.getParameter("id");
        String suId = request.getParameter("suId");
        JSONObject json = new JSONObject();
        String status = request.getParameter("status");
        String[] ids = id.split(",");
        int succnum = 0, failnum = 0;
        int tianmaoSum = 0;
        tianmaoSum = judgeTianmaoRole(suId, ids);
        if (tianmaoSum > 0)
        {
            // JSONObject jsons = new JSONObject();
            json.put("tianmaoSum", tianmaoSum);
            json.put("succnum", succnum);
            json.put("failnum", failnum);
            return json.toJSONString();
        }
        
        for (int i = 0; i < ids.length; i++)
        {
            String orderId = ids[i];
            Map<String, Object> order = orderDao.selectById(orderId);// 查询该订单
            if (order != null)
            {
                
                String orderStatus = order.get("status") + "";
                String agentId = order.get("agentId") + "";
                if (orderStatus.equals("3") || orderStatus.equals("1"))
                {// 订单从正在处理状态修改为失败状态
                    if (status.equals("4"))
                    {// 置为失败
                        boolean flag = chargeOrderSer.dealOrderFail(order, "4", "人工退款处理");
                        if (flag)
                        {
                            succnum++;
                            Map<String, Object> callbackMap = new HashMap<String, Object>();
                            callbackMap.put("status", AgentCallbackSer.CallbackStatus_Fail);
                            callbackMap.put("order", order);
                            mqProducer.sendDataToQueue(RabbitMqProducer.Callback_QueueKey,
                                SerializeUtil.getStrFromObj(callbackMap));
                        }
                        else
                        {
                            failnum++;
                        }
                    }
                    else if (status.equals("3"))
                    {// 置为成功
                        Map<String, Object> orderPathRecord = new HashMap<String, Object>();
                        orderPathRecord.putAll(order);
                        orderPathRecord.put("status", "3");
                        // 充值流水
                        chargeOrderSer.saveOrderPathRecord(orderPathRecord);
                        boolean flag = providerAccountSer.Charge(order);// 扣除上家余额
                        if (!flag)
                        {
                            log.error("扣除上家余额出错" + MapUtils.toString(order));
                            orderDao.deleteByPrimaryKey((String)order.get("id"));
                            order.put("resultCode", order.get("resultCode") + "|该笔订单扣除上家余额出现异常");
                            exceptionOrderDao.insertSelective(order);// 保存异常订单
                        }
                        else
                        {
                            order.put("status", 3);
                            order.put("endDate", new Timestamp(System.currentTimeMillis()));
                            int n = orderDao.updateOrder(order);
                            if (n < 1)
                            {
                                log.error("更新数据库出错" + MapUtils.toString(order));
                                orderDao.deleteByPrimaryKey((String)order.get("id"));
                                order.put("resultCode", order.get("resultCode") + "|该笔订单更新订单状态出现异常");
                                exceptionOrderDao.insertSelective(order);// 保存异常订单
                            }
                            else
                            {
                                succnum++;
                                Map<String, Object> callbackMap = new HashMap<String, Object>();
                                callbackMap.put("status", AgentCallbackSer.CallbackStatus_Success);
                                callbackMap.put("order", order);
                                mqProducer.sendDataToQueue(RabbitMqProducer.Callback_QueueKey,
                                    SerializeUtil.getStrFromObj(callbackMap));
                            }
                        }
                    }
                }
                else if ("4".equals(orderStatus) && "6fc1e7e29f4142f48110bc6c5286d723".equals(agentId))
                {
                    if (status.equals("3"))
                    {// 置为成功
                     // Map<String, Object> orderPathRecord = new HashMap<String, Object>();
                     // orderPathRecord.putAll(order);
                     // orderPathRecord.put("status", "3");
                     // 充值流水
                     // chargeOrderSer.saveOrderPathRecord(orderPathRecord);
                        order.put("status", 3);
                        order.put("resultCode", "天猫订单失败状态改为成功");
                        order.put("endDate", new Timestamp(System.currentTimeMillis()));
                        int n = orderDao.updateOrderByFail(order);
                        if (n < 1)
                        {
                            log.error("更新数据库出错" + MapUtils.toString(order));
                            orderDao.deleteByPrimaryKey((String)order.get("id"));
                            order.put("resultCode", order.get("resultCode") + "|该笔订单更新订单状态出现异常");
                            exceptionOrderDao.insertSelective(order);// 保存异常订单
                        }
                        else
                        {
                            succnum++;
                            Map<String, Object> callbackMap = new HashMap<String, Object>();
                            callbackMap.put("status", AgentCallbackSer.CallbackStatus_Success);
                            callbackMap.put("order", order);
                            mqProducer.sendDataToQueue(RabbitMqProducer.Callback_QueueKey,
                                SerializeUtil.getStrFromObj(callbackMap));
                        }
                    }
                }
                else
                {
                    failnum++;
                }
            }
        }
        json.put("tianmaoSum", tianmaoSum);
        json.put("succnum", succnum);
        json.put("failnum", failnum);
        return json.toJSONString();
    }
    
    public void expOrder(HttpServletResponse response, HttpServletRequest req)
    {
        Map<String, Object> m = getMaps(req); // 封装前台参数为map
//        String bizType = m.get("bizType").toString();
        String a = m.get("applyDate").toString();
        String applyDate = null;// DateTimeUtils.formatDate(a);
        String endDate = null;
        Date ad = null;
        Date ed = null;
        try
        {
            ad = DateTimeUtils.parseDate(m.get("applyDate").toString(), "yyyy-MM-dd HH:mm:ss");
            applyDate = DateTimeUtils.formatDate(ad, "yyyyMMddHHmmss");
            ed = DateTimeUtils.parseDate(m.get("endDate").toString(), "yyyy-MM-dd HH:mm:ss");
            endDate = DateTimeUtils.formatDate(ed, "yyyyMMddHHmmss");
        }
        catch (ParseException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        Map<String, Object> userInfoMap = getUser();
        String userid = userInfoMap.get("suId") + "";
        Map<String, Object> agentMap = agentDao.selectByUserId(userid);// 查询用户是否是代理商
        if (null != agentMap)
        {
            m.put("agentId", agentMap.get("id"));
        }
        
        String sheetName = "流量报表";
        String fileName = applyDate + "-" + endDate + sheetName;
        String filePath = req.getServletContext().getRealPath("/") + File.separator + "downloadFiles" + File.separator;
        log.error("cxj订单导出路径---->>>" + filePath);
        // 获取要导出的订单数据
        List<Map<String, Object>> orderList = orderDao.selectOrderByBizTypeAndApplyDate(m);
        
        // 组合处理要导出的订单数据
        Map<String, String[][]> map = initOrderInfo(sheetName, orderList, agentMap);
        
        try
        {
            ExportExcelUtil.xssfWrite(filePath + fileName + ".xlsx", map);
            // DownLoadUtil.downLoad(response, req, filePath, fileName, "2");
            FileDownload.fileDownload(response, filePath + fileName + ".xlsx", fileName + ".xlsx");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * <h5>功能描述:</h5> 组合导出数据
     *
     * @param sheetName excel表sheet名称
     * @param orderList 数据来源
     * @return
     *
     * @作者：zhangpj @创建时间：2017年3月22日
     */
    private Map<String, String[][]> initOrderInfo(String sheetName, List<Map<String, Object>> orderList,
        Map<String, Object> agentMap)
    {
        int index = 0;
        int keyIndex = 0;
        int size = orderList.size();
        
        String[][] orderData = new String[size + 1][50];
        if (null == agentMap)
        {
            orderData[0][0] = "上家订单号";
            orderData[0][1] = "平台订单号";
            orderData[0][2] = "代理商订单号";
            orderData[0][3] = "代理商名称";
            orderData[0][4] = "运营商";
            orderData[0][5] = "物理通道";
            orderData[0][6] = "手机号";
            orderData[0][7] = "流量包";
            orderData[0][8] = "地区";
            orderData[0][9] = "通道折扣价(元)";
            orderData[0][10] = "通道折扣";
            orderData[0][11] = "开始时间";
            orderData[0][12] = "状态";
            orderData[0][13] = "结束时间";
            orderData[0][14] = "原价(元)";
            orderData[0][15] = "代理商折扣价(元)";
            orderData[0][16] = "代理商折扣";
            orderData[0][17] = "利润(元)";
        }
        else
        {
            orderData[0][0] = "代理商订单号";
            orderData[0][1] = "代理商名称";
            orderData[0][2] = "运营商";
            orderData[0][3] = "手机号";
            orderData[0][4] = "地区";
            orderData[0][5] = "流量包";
            orderData[0][6] = "开始时间";
            orderData[0][7] = "状态";
            orderData[0][8] = "结束时间";
            orderData[0][9] = "原价(元)";
            orderData[0][10] = "代理商折扣价(元)";
        }
        
        for (int i = 0; i < size; i++)
        {
            index++;
            keyIndex = 0;
            Map<String, Object> map = orderList.get(i);
            
            String applyDate = StringUtil.objToString(map.get("applyDate"));
            String endDate = StringUtil.objToString(map.get("endDate"));
            String orderId = StringUtil.objToString(map.get("orderId"));
            String providerOrderId = StringUtil.objToString(map.get("providerOrderId"));
            String agentOrderId = StringUtil.objToString(map.get("agentOrderId"));
            String providerName = StringUtil.objToString(map.get("providerName"));
            String providerPhysicalChannel = StringUtil.objToString(map.get("providerPhysicalChannel"));
            String providerDiscount = StringUtil.objToString(map.get("providerDiscount"));
            String phone = StringUtil.objToString(map.get("phone"));
            String provinceCode = StringUtil.objToString(map.get("provinceCode"));
            String status = StringUtil.objToString(map.get("status"));
            String fee = StringUtil.objToString(map.get("fee"));
            String value = StringUtil.objToString(map.get("value"));
            String agentName = StringUtil.objToString(map.get("agentName"));
            String agentDiscount = StringUtil.objToString(map.get("agentDiscount"));
            String pkgName = StringUtil.objToString(map.get("pkgName"));
            
            switch (status)
            {
                case "1":
                    status = "提交成功";
                    break;
                case "2":
                    status = "提交失败";
                    break;
                case "3":
                    status = "充值成功";
                    break;
                case "4":
                    status = "充值失败";
                    break;
            }
            
            NumberFormat nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(3);
            double agentFee = 0;
            double providerFee = 0;
            String agentFeeStr = "";
            String providerFeeStr = "";
            // 判断客户折扣不为空
            if (null != agentDiscount && !"".equals(agentDiscount))
            {
                agentFee = Double.parseDouble(fee) * Double.parseDouble(agentDiscount);
            }
            if (agentFee != 0)
            {
                agentFeeStr = nf.format(agentFee) + "";
            }
            // 判断上家折扣不为空
            if (null != providerDiscount && !"".equals(providerDiscount))
            {
                providerFee = Double.parseDouble(fee) * Double.parseDouble(providerDiscount);
            }
            if (providerFee != 0)
            {
                providerFeeStr = nf.format(providerFee) + "";
            }
            // 利润
            double profit = agentFee - providerFee;
            String profitStr = nf.format(profit) + "";
            if (null == agentMap)
            {
                orderData[index][keyIndex++] = providerOrderId;
                orderData[index][keyIndex++] = orderId;
                orderData[index][keyIndex++] = agentOrderId;
                orderData[index][keyIndex++] = agentName;
                orderData[index][keyIndex++] = providerName;
                orderData[index][keyIndex++] = providerPhysicalChannel;
                orderData[index][keyIndex++] = phone;
                orderData[index][keyIndex++] = pkgName;
                orderData[index][keyIndex++] = provinceCode;
                orderData[index][keyIndex++] = providerFeeStr;
                orderData[index][keyIndex++] = providerDiscount;
                orderData[index][keyIndex++] = applyDate;
                orderData[index][keyIndex++] = status;
                orderData[index][keyIndex++] = endDate;
                orderData[index][keyIndex++] = fee;
                orderData[index][keyIndex++] = agentFeeStr;
                orderData[index][keyIndex++] = agentDiscount;
                orderData[index][keyIndex++] = profitStr;
            }
            else
            {
                orderData[index][keyIndex++] = agentOrderId;
                orderData[index][keyIndex++] = agentName;
                orderData[index][keyIndex++] = providerName;
                orderData[index][keyIndex++] = phone;
                orderData[index][keyIndex++] = provinceCode;
                orderData[index][keyIndex++] = pkgName;
                orderData[index][keyIndex++] = applyDate;
                orderData[index][keyIndex++] = status;
                orderData[index][keyIndex++] = endDate;
                orderData[index][keyIndex++] = fee;
                orderData[index][keyIndex++] = agentFeeStr;
            }
            
        }
        
        Map<String, String[][]> map = new TreeMap<String, String[][]>();
        map.put(sheetName, orderData);
        
        return map;
    }
    
    /**
     * @功能描述： 跳转到订单详细参数页面
     *
     * @作者：zhangpj @创建时间：2017年4月26日
     * @param req
     */
    public void orderParamPage(HttpServletRequest req)
    {
        Map<String, Object> orderParam = selectOrderParam(req);
        req.setAttribute("orderParam", orderParam);
        req.setAttribute("orderType", "1");
    }
    
    /**
     * @功能描述： 获取订单详细参数信息
     *
     * @作者：zhangpj @创建时间：2017年4月26日
     * @param req
     * @return
     */
    public String getOrderParam(HttpServletRequest req)
    {
        Map<String, Object> orderParam = selectOrderParam(req);
        return JSONObject.toJSONString(orderParam);
    }
    
    /**
     * @功能描述： 查询订单详细参数信息
     *
     * @作者：zhangpj @创建时间：2017年4月26日
     * @param req
     * @return
     */
    public Map<String, Object> selectOrderParam(HttpServletRequest req)
    {
        Map<String, Object> m = getMaps(req); // 封装前台参数为map
        String phone = String.valueOf(m.get("phone"));
        String agentOrderId = String.valueOf(m.get("agentOrderId"));
        // 获取登录人Id
        Map<String, Object> userInfoMap = getUser();
        String userid = userInfoMap.get("suId") + "";
        // 根据用户Id查询agent表，若不为null则代表用户为代理商登陆
        Map<String, Object> agentMap = agentDao.selectByUserId(userid);
        if (agentMap != null)
        {
            // 得到代理商Id，查询其自身订单和其子集订单
            String agentParentId = agentMap.get("id") + "";
            m.put("agentParentId", agentParentId);
        }
        Map<String, Object> orderParam = null;
        if ((null != phone && !phone.equals("")) || (null != agentOrderId && !agentOrderId.equals("")))
        {
            // 根据订单编号或者电话号码获取最新一条的订单信息
            Map<String, String> orderMap = orderDao.selectFastNewOrderByPhone(m);
            if (null != orderMap)
            {
                agentOrderId = orderMap.get("order_id");
                m.put("orderId", agentOrderId);
                // 1.获取订单参数
                orderParam = orderDao.selectOrderParam(m);
                
                // 2.获取可用流量包
                Map<String, String> param = new HashMap<String, String>();
                param.put("agentId", orderParam.get("agentId").toString());
                param.put("providerId", orderParam.get("providerId").toString());
                param.put("dataType", orderParam.get("dataType").toString());
                param.put("provinceCode", orderParam.get("provinceCode").toString());
                String dataType = orderParam.get("dataType").toString();
                if ("2".equals(dataType))
                {
                    // 流量
                    param.put("value", orderParam.get("value").toString());
                }
                
                Map<String, Object> pkg = dataPkgDao.selectDataPkgForAgent(param);
                if (pkg == null)
                {
                    param.put("provinceCode", "全国");
                    pkg = dataPkgDao.selectDataPkgForAgent(param);
                }
                
                // 3.获取可用通道列表
                Map<String, Object> dispatcherParam = new HashMap<String, Object>();
                dispatcherParam.put("pkgId", orderParam.get("pkgId"));
                dispatcherParam.put("providerId", orderParam.get("providerId"));
                dispatcherParam.put("provinceCode", orderParam.get("provinceCode"));
                List<Map<String, Object>> dpList =
                    providerDataDispatcherDao.selectProviderPhysicalChannel(dispatcherParam);
                
                orderParam.put("result", "success");
                orderParam.put("pkg", pkg);
                orderParam.put("dispatcherParam", dpList);
            }
        }
        
        return orderParam;
    }
    
    /**
     * 获取主页上家需要显示的数据
     * 
     * @author lks 2017年5月19日下午3:12:25
     * @param request
     * @param response
     * @return
     */
    public String countPhysicalChannelProfit(HttpServletRequest request, HttpServletResponse response)
    {
        JSONObject json = new JSONObject();
        Map<String, Object> param = getMaps(request);
        Map<String, Object> user = getUser();
        String suid = user.get("suId") + "";// 用户Id
        String agentId = "";
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        if (judgeAgentRole(suid))
        {// 如果有代理商角色
            agentId = agentDao.selectAgentIdByUserid(suid);
            if (agentId != null && !agentId.equals(""))
            {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("agentId", agentId);
                map.putAll(param);
                dataList = orderDao.selectPhysicalChannelProfit(map);
            }
        }
        else
        {
            dataList = orderDao.selectPhysicalChannelProfit(param);
        }
        json.put("data", JSONObject.toJSON(dataList));
        return json.toJSONString();
    }
    
    /**
     * 获取主页需要显示的数据
     * 
     * @author lks 2017年6月3日下午2:17:15
     * @param request
     * @param response
     * @return
     */
    public String getChartsData(HttpServletRequest request, HttpServletResponse response)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> dateList = new ArrayList<String>();
        for (int i = 29; i >= 0; i--)
        {
            Calendar theCa = Calendar.getInstance();
            theCa.setTime(new Date());
            theCa.add(Calendar.DATE, -i);
            Date date = theCa.getTime();
            dateList.add(DateUtil.formatDate(date, "yyyy-MM-dd"));
        }
        map.put("dateData", dateList);
        Map<String, Object> agentParam = new HashMap<String, Object>();
        agentParam.put("num", 5);
        agentParam.put("startDate", dateList.get(0));
        agentParam.put("endDate", dateList.get(dateList.size() - 1));
        List<Map<String, Object>> agentList = orderDao.selectForntAgent(agentParam);
        List<String> agentNameList = new ArrayList<String>();
        List<Echarts> seriesList = new ArrayList<Echarts>();
        for (int i = 0; i < agentList.size(); i++)
        {
            Map<String, Object> agentMap = agentList.get(i);
            agentNameList.add((String)agentMap.get("name"));
            List<String> chartsDataList = getDataList(dateList, agentMap);
            // map.put(agentMap.get("name")+"", chartsDataList);
            Echarts charts = new Echarts(agentMap.get("name") + "", "line", "销量", chartsDataList);
            seriesList.add(charts);
        }
        map.put("agentNameData", agentNameList);
        map.put("seriesData", seriesList);
        JSONObject json = (JSONObject)JSONObject.toJSON(map);
        return json.toJSONString();
    }
    
    public List<String> getDataList(List<String> dateList, Map<String, Object> agentMap)
    {
        agentMap.put("dateList", dateList);
        List<String> dataList = orderDao.selectAgentChartsData(agentMap);
        return dataList;
    }
    
    /**
     * 判断用户是否具有代理商的角色
     * 
     * @author lks 2017年5月18日下午2:36:33
     * @param suid
     * @return
     */
    public boolean judgeAgentRole(String suid)
    {
        boolean flag = false;
        List<Map<String, Object>> list = sysUserRoleDao.getHasSysRoleList(suid);
        for (Map<String, Object> role : list)
        {
            String roleName = role.get("srName") + "";
            if (roleName.equals("代理商"))
            {
                flag = true;
            }
        }
        return flag;
    }
    
    /**
     * @Title:judgeTianmaoRole
     * @Description: 判断是否是天猫订单(这里用一句话描述这个方法的作用)
     * @author CXJ
     * @date 2017年6月7日 下午5:12:10
     * @param @param suId
     * @param @param ids
     * @param @return
     * @return int 返回类型
     * @throws
     */
    public int judgeTianmaoRole(String suId, String[] ids)
    {
        int tianmaoSum = 0;
        List<Map<String, Object>> dataList = sysUserRoleDao.getHasSysRoleList(suId);
        boolean roleFlag = false;
        for (Map<String, Object> map : dataList)
        {
            String srName = map.get("srName") + "";
            if ("天猫".equals(srName) || "技术运维".equals(srName))
            {
                roleFlag = true;
            }
        }
        if (roleFlag)
        {
            
            for (int i = 0; i < ids.length; i++)
            {
                String orderId = ids[i];
                Map<String, Object> order = orderDao.selectById(orderId);// 查询该订单
                if (order != null)
                {
                    String agentId = order.get("agentId") + "";
                    if (!"6fc1e7e29f4142f48110bc6c5286d723".equals(agentId)
                        && !"81c2390df095475f86f0e9c6dff1cfd2".equals(agentId))
                    {
                        tianmaoSum += 1;
                    }
                }
            }
        }
        
        return tianmaoSum;
    }
}
